package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author ChenPi
 * @description Redis实现全局ID生成器，ID结构为：时间戳 + 自增序列号（二进制）
 * @since 2024/09/13 15:04
 */
@Component
public class RedisIdWorker {

    /**
     * 开始时间戳
     */
    private final static long BEGIN_TIMESTAMP = 1725883200L;
    /**
     * 序列号的位数
     */
    private final static long COUNT_BITS = 32;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 获取 Spring 应用名称
    @Value("${spring.application.name}")
    private String projectName;

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024, 9, 9, 12, 0, 0);
        long epochSecond = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("epochSecond = " + epochSecond);
    }

    public long nextId(String prefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSeconds = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSeconds - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1 获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2 自增序列号
        long count = stringRedisTemplate.opsForValue().increment(projectName + ":incr:" + prefix + ":" + date);

        // 3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }
}
